package cn.shequren.communityPeople.home.ui.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Process;
import android.support.annotation.Nullable;
import android.widget.ImageView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.jz.community.basecomm.base.BaseMvpActivity;
import com.jz.community.basecomm.base.BaseX5WebActivity;
import com.jz.community.basecomm.bean.BaseCommLocateInfo;
import com.jz.community.basecomm.bean.RegionsBean;
import com.jz.community.basecomm.constant.RequseResultConstants;
import com.jz.community.basecomm.glideConfig.GlideApp;
import com.jz.community.basecomm.loaction.LocationManager;
import com.jz.community.basecomm.routerUtils.RouterCommonUtils;
import com.jz.community.basecomm.routerUtils.RouterIntentConstant;
import com.jz.community.basecomm.utils.BaseSpUtils;
import com.jz.community.basecomm.utils.LoggerUtils;
import com.jz.community.basecomm.utils.Preconditions;
import com.jz.community.basecomm.utils.RxScreenshotDetector;
import com.jz.community.basecomm.utils.WpToast;
import com.jz.community.basecomm.utils.eventbus.AppEvent;
import com.jz.community.basecomm.utils.eventbus.EventConfig;
import com.jz.community.commview.commPagerAdapter.CustomViewPager;
import com.jz.community.modulemine.ui.fragment.MineFragment;
import com.jz.community.moduleothers.scan.ui.QRHomeFragment;
import com.jz.community.moduleshopping.groupbuying.ui.GroupBuyingFragment;
import com.jz.community.moduleshopping.shopCart.ui.ShoppingCartFragment;
import com.jz.community.moduleshoppingguide.home.bean.HomeFindBean;
import com.jz.community.moduleshoppingguide.home.ui.fragment.HomeFragment;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import cn.shequren.communityPeople.R;
import cn.shequren.communityPeople.home.bean.VersionBean;
import cn.shequren.communityPeople.home.presenter.MainPresenter;
import cn.shequren.communityPeople.home.ui.MainView;
import cn.shequren.communityPeople.home.ui.adapter.CommonViewPagerAdapter;
import cn.shequren.communityPeople.home.ui.view.DrawableTabItem;
import cn.shequren.communityPeople.home.ui.view.GlideTabItem;
import cn.shequren.communityPeople.home.ui.view.VersionUpdateDialog;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import me.majiajie.pagerbottomtabstrip.NavigationController;
import me.majiajie.pagerbottomtabstrip.PageNavigationView;
import me.majiajie.pagerbottomtabstrip.item.BaseTabItem;
import me.majiajie.pagerbottomtabstrip.item.NormalItemView;
import me.majiajie.pagerbottomtabstrip.listener.OnTabItemSelectedListener;

@Route(path = RouterIntentConstant.APP_MODULE_MAIN)
public class MainActivity extends BaseMvpActivity<MainView.View, MainPresenter> implements MainView.View {

    @BindView(R.id.main_vp)
    CustomViewPager mainVp;
    @BindView(R.id.main_tab)
    PageNavigationView mainTab;
    @BindView(R.id.main_center_iv)
    ImageView mainCenterIv;

    private HomeFragment homeFragment;
    private ShoppingCartFragment shoppingFragment;
    private MineFragment mineFragment;
    private GroupBuyingFragment groupBuyingFragment;
    private QRHomeFragment qrHomeFragment;

    private String[] nativeButtomText = {"首页", "拼团购", "购物车", "我的"};

    private long exitTime = 0;
    private int bgColor = 0xffffffff;
    private int viewPageIndex;


    @Override
    public Context getContext() {
        return this;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getContentView() {
        return R.layout.activity_main;
    }

    //初始化相关截图监听
    @SuppressLint("CheckResult")
    private void initScreenShotDetector() {
        RxScreenshotDetector.start(this)
                .compose(bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<String>() {
                               @Override
                               public void accept(String picPath) throws Exception {
                                   //  处理截图分享逻辑
                                   if (viewPageIndex == 2) {
                                       WpToast.l(MainActivity.this, "该码仅用于付款，请勿发给他人");
                                   }
                               }
                           },
                        Throwable::printStackTrace);
    }

    @Override
    protected void initView() {
        homeFragment = new HomeFragment();
        shoppingFragment = new ShoppingCartFragment();
        mineFragment = new MineFragment();
        groupBuyingFragment = new GroupBuyingFragment();
        qrHomeFragment = new QRHomeFragment();
        EventBus.getDefault().register(this);
    }


    /**
     * @param message
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(AppEvent message) {
        if (message.tag == EventConfig.HOME) {
            mainVp.setCurrentItem(0, false);
        }
    }


    @Override
    protected MainPresenter createPresenter() {
        return new MainPresenter(this);
    }

    @Override
    protected void initDatas() {

        getByDataBundle();


        //不是第一次进入app直接获取本地缓存经纬度
        if (BaseSpUtils.getInstance().getBoolean(this, "isFirstOver")) {
            initHomePage();
            getTabData();
        } else {
            //首次进入app通过定位获取经纬度
            beginLocation();
        }
        //版本更新接口
        mPresenter.updateVersion(getAppVersionName());


    }

    /**
     * 获取应用的当前版本名称
     *
     * @return
     */
    private String getAppVersionName() {
        try {
            return getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }

    //获取getIntent数据
    private void getByDataBundle() {
        String goodsUrl = getIntent().getExtras().getString("goodsUrl");
        String url = getIntent().getExtras().getString("url");
        String title = getIntent().getExtras().getString("title");
        //商品详情
        if (!Preconditions.isNullOrEmpty(goodsUrl)) {
            RouterCommonUtils.startParameterActivity(this, RouterIntentConstant.MODULE_SHOPPING_GOODS_DETAIL, "url", goodsUrl, RequseResultConstants.REQUEST_HTML_CODE);
            return;
            //Html5
        } else if (!Preconditions.isNullOrEmpty(url)) {
            startActivityForResult(new Intent(this, BaseX5WebActivity.class)
                    .putExtra("url", url)
                    .putExtra("title", title), RequseResultConstants.REQUEST_HTML_CODE);
            return;
        }
    }

    private void openUpdateDialog(VersionBean entity) {
        VersionUpdateDialog versionDialog = new VersionUpdateDialog(mActivity, entity);
        versionDialog.show();
    }

    private void beginLocation() {
        LocationManager locationManager = new LocationManager();
        locationManager.getLocation(result -> {
            if (result.mResultId == 0) {
                findIdByCityCode(result.mLocation.mCity);
                BaseSpUtils.getInstance().putBoolean(this, "isFirstOver", true);
                BaseCommLocateInfo locateInfo = new BaseCommLocateInfo();
                locateInfo.lon = result.mLocation.mLongitude + "";
                locateInfo.lat = result.mLocation.mLatitude + "";
                locateInfo.city = result.mLocation.mCity;
                locateInfo.citycode = result.mLocation.mCityCode;
                BaseSpUtils.getInstance().setCurrentCommuity(this, locateInfo);
                initHomePage();
                getTabData();
            } else {
                BaseSpUtils.getInstance().putBoolean(this, "isFirstOver", true);
                initHomePage();
                getTabData();
            }
        }, this);
    }

    private void findIdByCityCode(String cityName) {
        RegionsBean regionsBean = BaseSpUtils.getInstance().getRegionList(this);
        if (regionsBean != null && regionsBean.get_embedded().getContent().size() > 1) {
            for (int i = 0; i < regionsBean.get_embedded().getContent().size(); i++) {
                if (cityName.contains(regionsBean.get_embedded().getContent().get(i).getName())) {
                    BaseSpUtils.getInstance().setRegion(getContext(), regionsBean.get_embedded().getContent().get(i));
                    break;
                }
            }
        } else {
            BaseSpUtils.getInstance().setRegion(getContext(), regionsBean.get_embedded().getContent().get(0));
        }
    }

    private void getTabData() {
        RegionsBean.EmbeddedBean.ContentBean region = BaseSpUtils.getInstance().getRegion(getContext());
        if (region != null) {
            mPresenter.getChunnelHomePage(0, 100, region.getId() + "");
        }
    }

    @Override
    public void setUpdateData(VersionBean entity) {
        openUpdateDialog(entity);
    }


    @Override
    public void showHomeChannel(HomeFindBean homeFindBean) {
        for (int i = 0; i < homeFindBean.get_embedded().getContent().size(); i++) {
            if (homeFindBean.get_embedded().getContent().get(i).getType() == 7) {
                initBottomSuccess(homeFindBean.get_embedded().getContent().get(i).getChunnelHomePage());
            }
        }
    }

    @Override
    public void showError(String s, int type) {
        if (type == 0) {
            initHomePage();
            initBottomFailed();
        }
    }

    private void initHomePage() {
        CommonViewPagerAdapter pagerAdapter = new CommonViewPagerAdapter(getSupportFragmentManager());
        pagerAdapter.addFragment(nativeButtomText[0], homeFragment);
        pagerAdapter.addFragment(nativeButtomText[1], groupBuyingFragment);
        pagerAdapter.addFragment("", qrHomeFragment);
        pagerAdapter.addFragment(nativeButtomText[2], shoppingFragment);
        pagerAdapter.addFragment(nativeButtomText[3], mineFragment);
        mainVp.setAdapter(pagerAdapter);
        mainVp.setCurrentItem(0, false);
        mainVp.setOffscreenPageLimit(4);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == HomeFragment.REQUEST_CODE_LOCATION && resultCode == 1) {
            if (null != homeFragment) {
                homeFragment.getHomeData();
            }
        }

        if (requestCode == RequseResultConstants.REFESH_TOKEN_CODE && resultCode == RESULT_CANCELED) {
            if (null != homeFragment) {
                homeFragment.getHomeData();
            }
        }

        if (requestCode == RequseResultConstants.REQUEST_HTML_CODE && resultCode == RESULT_OK) {
            if (null != homeFragment) {
                homeFragment.getHomeData();
            }
        }

        if (requestCode == RequseResultConstants.REQUEST_HTML_CODE && resultCode == RESULT_CANCELED) {
            if (null != homeFragment) {
                homeFragment.getHomeData();
            }
        }
    }

    private void initBottomSuccess(List<HomeFindBean.EmbeddedBean.ContentBean.ChunnelHomePageBean> bottomTabList) {
        if (bottomTabList.size() == 5) {
            NavigationController navigationController = mainTab.custom()
                    .addItem(newGlideTabItem(bottomTabList.get(0).getDefaultImage(), bottomTabList.get(0).getDefaultSelectionImage(), "首页"))
                    .addItem(newGlideTabItem(bottomTabList.get(1).getDefaultImage(), bottomTabList.get(1).getDefaultSelectionImage(), "拼团购"))
                    .addItem(newNormalItem(0, 0, ""))
                    .addItem(newGlideTabItem(bottomTabList.get(3).getDefaultImage(), bottomTabList.get(3).getDefaultSelectionImage(), "购物车"))
                    .addItem(newGlideTabItem(bottomTabList.get(4).getDefaultImage(), bottomTabList.get(4).getDefaultSelectionImage(), "我的"))
                    .build();

            LoggerUtils.fLog().i("aaaaaaaaaaa " + bottomTabList.get(2).getDefaultImage());
            GlideApp.with(this)
                    .load(bottomTabList.get(2).getDefaultImage())
                    .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                    .into(mainCenterIv);
            //自动适配ViewPager页面切换
            navigationController.setupWithViewPager(mainVp);

            navigationController.addTabItemSelectedListener(new OnTabItemSelectedListener() {
                @Override
                public void onSelected(int index, int old) {
                    viewPageIndex = index;
                    if (homeFragment != null){
                        homeFragment.setViewPagerPosition(index);
                    }
                }

                @Override
                public void onRepeat(int index) {
                    switch (index) {
                        case 0:
                            if (null != homeFragment) {
                                homeFragment.refreshData();
                            }
                            break;
                        case 1:
                            if (groupBuyingFragment != null) {
                                groupBuyingFragment.refreshData();
                            }
                            break;
                        case 3:
                            if (null != shoppingFragment) {
                                shoppingFragment.refreshCart();
                            }
                    }

                }
            });
        } else {
            initBottomFailed();
        }
    }

    private void initBottomFailed() {
        NavigationController navigationController = mainTab.custom()
                .addItem(newDrawableTabItem(R.mipmap.nav_ic_home, R.mipmap.nav_ic_home_active, "首页"))
                .addItem(newDrawableTabItem(R.mipmap.nav_ic_order, R.mipmap.nav_ic_order_active, "拼团购"))
                .addItem(newNormalItem(0, 0, ""))
                .addItem(newDrawableTabItem(R.mipmap.nav_ic_cart, R.mipmap.nav_ic_cart_active, "购物车"))
                .addItem(newDrawableTabItem(R.mipmap.nav_ic_my, R.mipmap.nav_ic_my_active, "我的"))
                .build();
        mainCenterIv.setImageResource(R.mipmap.home_center);
        mainTab.setBackgroundColor(bgColor);
        //自动适配ViewPager页面切换
        navigationController.setupWithViewPager(mainVp);

        navigationController.addTabItemSelectedListener(new OnTabItemSelectedListener() {
            @Override
            public void onSelected(int index, int old) {
                viewPageIndex = index;
                if (homeFragment != null){
                    homeFragment.setViewPagerPosition(index);
                }
            }

            @Override
            public void onRepeat(int index) {
                switch (index) {
                    case 0:
                        if (null != homeFragment) {
                            homeFragment.refreshData();
                        }
                        break;
                    case 1:
                        if (groupBuyingFragment != null) {
                            groupBuyingFragment.refreshData();
                        }
                        break;
                    case 3:
                        if (null != shoppingFragment) {
                            shoppingFragment.refreshCart();
                        }
                        break;
                    default:
                        break;
                }

            }
        });
    }

    //创建一个Item
    private BaseTabItem newNormalItem(int drawable, int checkedDrawable, String text) {
        NormalItemView normalItemView = new NormalItemView(this);
        normalItemView.initialize(drawable, checkedDrawable, text);
        normalItemView.setTextDefaultColor(0xFF333333);
        normalItemView.setTextCheckedColor(0xFFF52D36);
        return normalItemView;
    }

    //加载网络图片
    private BaseTabItem newGlideTabItem(String tabDefaultImgUrl, String
            tabCheckedImgUrl, String title) {
        GlideTabItem glideTabItem = new GlideTabItem(this);
        glideTabItem.initialize(tabDefaultImgUrl, tabCheckedImgUrl, title);
        glideTabItem.setTextDefaultColor(0xFF333333);
        glideTabItem.setTextCheckedColor(0xFFF52D36);
        return glideTabItem;
    }

    //加载本地图片
    private BaseTabItem newDrawableTabItem(int drawable, int checkedDrawable, String title) {
        DrawableTabItem drawableTabItem = new DrawableTabItem(this);
        drawableTabItem.initialize(drawable, checkedDrawable, title);
        drawableTabItem.setTextDefaultColor(0xFF333333);
        drawableTabItem.setTextCheckedColor(0xFFF52D36);
        return drawableTabItem;
    }


    @Override
    protected void onResume() {
        super.onResume();
        initScreenShotDetector();
    }


    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onBackPressedSupport() {
        if (System.currentTimeMillis() - exitTime > 2000) {
            WpToast.l(this, getString(R.string.exit_hint));
            exitTime = System.currentTimeMillis();
        } else {
            super.onBackPressedSupport();
            int pid = Process.myPid();
            Process.killProcess(pid);
        }
    }
}
